package com.hcms.admin.aop;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.hcms.admin.security.AdminUserDetails;
import com.hcms.admin.service.ISysAdminLogService;
import com.hcms.mybatis.entity.SysAdmin;
import com.hcms.mybatis.entity.SysAdminLog;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Aspect
@Component
public class SysAdminLogAop {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ISysAdminLogService sysAdminLogService;

    @Pointcut("execution(* com.hcms.admin.controller..*(..))")
    public void log() {
    }

    @Before("log()")
    public void doBeforeCheck() {
        logger.info("Run doBeforeCheck()");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof AdminUserDetails) {
                AdminUserDetails details = (AdminUserDetails) principal;
                SysAdmin sysAdmin = details.getSysAdmin();
                //获取个参数
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
                HttpServletRequest request = requestAttributes.getRequest();
                String method = request.getMethod();
                String requestURI = request.getRequestURI();
                String clientIP = ServletUtil.getClientIP(request);
                UserAgent userAgent = UserAgentUtil.parse(request.getHeader("user-agent"));
                String browserName = userAgent.getBrowser().getName();
                //保存日志
                SysAdminLog entity = new SysAdminLog();
                entity.setUsername(sysAdmin.getUsername());
                entity.setMethod(method.toUpperCase());
                entity.setAddress(requestURI);
                entity.setIp(clientIP);
                entity.setUserAgent(browserName);
                entity.setCreateTime(new Date());
                sysAdminLogService.save(entity);
            }
        }
    }
}
